﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Core.Manager {
    public class PublishedMessageManager {
        private static IObjectManager<PublishedMessage> _messages;
        private static object _lockObject = new object();
        const string MESSAGE_STORE_ALIAS = "MessageStore";

        public static DefaultMessageHandler<PublishedMessage> GetHandler() {
            return new DefaultMessageHandler<PublishedMessage>(ConfigurationProvider.ComponentContainerConfig.Address, MESSAGE_STORE_ALIAS,
                ConfigurationProvider.ComponentContainerConfig.Interval, ConfigurationProvider.ComponentContainerConfig.BatchSize);
        }

        private static IObjectManager<PublishedMessage> Messages {
            get {
                if (_messages == null)
                    _messages = ObjectManager<PublishedMessage>.Create(ConfigurationProvider.ServiceBusConfig.MessageStoreAddress, MESSAGE_STORE_ALIAS);
                return _messages;
            }
        }

        /// <summary>
        /// Add new message to the underlying data store
        /// </summary>
        /// <param name="message"></param>
        public static void Attach(PublishedMessage message) {
            Messages.Attach(message);
        }

        /// <summary>
        /// Add new messages to the underlying data store
        /// </summary>
        /// <param name="messages"></param>
        public static void AttachMany(IEnumerable<PublishedMessage> messages) {
            Messages.AttachMany(messages);
        }

        /// <summary>
        /// Find all PublishedMessage Storage and store current message in each
        /// </summary>
        /// <param name="message"></param>
        public static void Store(PublishedMessage message) {
            lock (_lockObject) {
                var storages = MessageStoreManager.Stores;
                for (var i = 0; i < storages.Count; i++) storages[i].Store(message);
            }
        }
    }
}
